from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'

socketio = SocketIO()
socketio.init_app(app, cors_allowed_origins='*')
from flask import g, jsonify
name_space = '/echo'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/push')
def push_once():

    return 'done!'

# 连接自动执行
@socketio.on('connect', namespace=name_space)
def connected_msg():
    print('client connected.')

# 断开自动执行
@socketio.on('disconnect', namespace=name_space)
def disconnect_msg():
    print('client disconnected.')
# 接收消息自动执行
@socketio.on('message', namespace=name_space)
def handle_message(data):
    emit('message',  {'data': "test message!"} , namespace=name_space)
    print('received message: ' + data)

@socketio.on('json', namespace=name_space)
def handle_json(json):
    print('received json: ' + str(json))

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000,debug=True)
